<template>
  <div class="new-address-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-container">
        <div class="logo">
          <i class="logo-icon">📦</i>
          <span class="logo-text">快递面单录入系统</span>
        </div>
        <div class="nav-actions">
          <button class="back-btn" @click="goBack">
            <i class="back-icon">←</i>
            返回首页
          </button>
        </div>
      </div>
    </nav>

    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
          <div class="header-icon">📍</div>
          <h1>新建联系人地址</h1>
          <p class="subtitle"> 智能地址识别与录入</p>
        </div>

        <!-- 文本识别区域 -->
        <div class="text-recognition-card">
          <div class="card-header">
            <i class="card-icon">🔍</i>
            <h2>智能文本识别</h2>
          </div>
          <div class="card-content">
            <p class="section-description">输入包含姓名、手机号和地址的文本，系统将自动识别并填充表单</p>

            <div class="text-input-container">
              <div class="input-header">
                <label class="input-label">输入文本</label>
                <span class="char-count">{{ textInput.length }}/500</span>
              </div>
              <textarea
                  v-model="textInput"
                  placeholder="例如：&#10;张三，13812345678，北京市朝阳区建国门外大街1号国贸大厦A座12层&#10;李四，13987654321，上海市浦东新区陆家嘴环路1000号汇亚大厦"
                  maxlength="500"
                  class="styled-textarea"
              ></textarea>
              <div class="input-footer">
                <div class="example-text">
                  <i class="hint-icon">💡</i>
                  <span>支持格式：姓名，手机号，地址（每行一个联系人）</span>
                </div>
              </div>
            </div>

            <button class="recognize-btn" @click="handleRecognize" :disabled="!textInput.trim()">
              <i class="btn-icon">✨</i>
              {{ textInput.trim() ? '智能识别' : '请输入文本' }}
            </button>
          </div>
        </div>

        <!-- 联系人信息表单 -->
        <div class="contact-form-card">
          <div class="card-header">
            <i class="card-icon">👤</i>
            <h2>联系人详细信息</h2>
          </div>
          <div class="card-content">
            <form @submit.prevent="handleSubmit" class="styled-form">
              <div class="form-row">
                <div class="form-group">
                  <label for="name" class="form-label">
                    <span class="label-text">姓名</span>
                    <span class="required-mark">*</span>
                  </label>
                  <div class="input-wrapper">
                    <i class="input-icon">👤</i>
                    <input
                        type="text"
                        id="name"
                        v-model="formData.name"
                        placeholder="请输入联系人姓名"
                        required
                        class="styled-input"
                    >
                  </div>
                </div>

                <div class="form-group">
                  <label for="phone" class="form-label">
                    <span class="label-text">手机号</span>
                    <span class="required-mark">*</span>
                  </label>
                  <div class="input-wrapper">
                    <i class="input-icon">📱</i>
                    <input
                        type="tel"
                        id="phone"
                        v-model="formData.phone"
                        placeholder="请输入11位手机号码"
                        required
                        @input="formatPhone"
                        maxlength="11"
                        class="styled-input"
                    >
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label class="form-label">
                  <span class="label-text">省市区</span>
                  <span class="required-mark">*</span>
                </label>
                <div class="address-selectors">
                  <div class="select-wrapper">
                    <i class="select-icon">🏙️</i>
                    <select id="province" v-model="formData.province" required @change="onProvinceChange"
                            class="styled-select">
                      <option value="">请选择省份</option>
                      <option v-for="province in provinces" :key="province" :value="province">
                        {{ province }}
                      </option>
                    </select>
                  </div>

                  <div class="select-wrapper">
                    <i class="select-icon">🏢</i>
                    <select id="city" v-model="formData.city" required @change="onCityChange" class="styled-select"
                            :disabled="!formData.province">
                      <option value="">请选择城市</option>
                      <option v-for="city in cities" :key="city" :value="city">
                        {{ city }}
                      </option>
                    </select>
                  </div>

                  <div class="select-wrapper">
                    <i class="select-icon">📍</i>
                    <select id="district" v-model="formData.district" required class="styled-select"
                            :disabled="!formData.city">
                      <option value="">请选择区县</option>
                      <option v-for="district in districts" :key="district" :value="district">
                        {{ district }}
                      </option>
                    </select>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label for="detailAddress" class="form-label">
                  <span class="label-text">详细地址</span>
                  <span class="required-mark">*</span>
                </label>
                <div class="input-wrapper">
                  <i class="input-icon">🏠</i>
                  <input
                      type="text"
                      id="detailAddress"
                      v-model="formData.detailAddress"
                      placeholder="输入小区、写字楼或街道门牌号"
                      required
                      class="styled-input"
                  >
                </div>
                <div class="hint-text">
                  <i class="hint-icon">💡</i>
                  输入详细地址信息，如：xx小区xx栋xx单元xx室
                </div>
              </div>

              <div class="form-actions">
                <button type="button" class="cancel-btn" @click="goBack">
                  取消
                </button>
                <button type="submit" class="save-btn" :disabled="loading || !isFormValid">
                  <i class="btn-icon" v-if="!loading">💾</i>
                  <span class="loading-spinner" v-if="loading"></span>
                  {{ loading ? '保存中...' : '保存地址' }}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="footer">
      <div class="footer-content">
        <p class="footer-text">2025 © 523300264225 徐烨</p>
        <p class="footer-subtext">J2EE程序设计 - 快递面单录入系统</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {addressAPI} from '../api'
import chinaRegions from '../data/china-regions.json'

const router = useRouter()
const textInput = ref('')
const loading = ref(false)

const formData = reactive({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: ''
})

// 计算属性
const provinces = computed(() => Object.keys(chinaRegions))
const cities = computed(() => formData.province ? Object.keys(chinaRegions[formData.province] || {}) : [])
const districts = computed(() => formData.city ? (chinaRegions[formData.province]?.[formData.city] || []) : [])
const isFormValid = computed(() => {
  return formData.name.trim() &&
      /^1[3-9]\d{9}$/.test(formData.phone.trim()) &&
      formData.province &&
      formData.city &&
      formData.district &&
      formData.detailAddress.trim()
})

onMounted(() => {
  const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || 'null')
  if (!currentUser) {
    router.push('/login')
  }
})

const onProvinceChange = () => {
  formData.city = ''
  formData.district = ''
}

const onCityChange = () => {
  formData.district = ''
}

const formatPhone = (event) => {
  let value = event.target.value.replace(/\D/g, '')
  if (value.length > 11) {
    value = value.slice(0, 11)
  }
  formData.phone = value
}

const parseAddress = (address) => {
  const allProvinces = Object.keys(chinaRegions)
  let foundProvince = ''
  let foundCity = ''
  let foundDistrict = ''
  let detail = address

  // 查找省份
  for (const province of allProvinces) {
    if (address.includes(province)) {
      foundProvince = province
      detail = detail.replace(province, '')
      break
    }
  }

  // 查找城市
  if (foundProvince && chinaRegions[foundProvince]) {
    const cities = Object.keys(chinaRegions[foundProvince])
    for (const city of cities) {
      if (address.includes(city)) {
        foundCity = city
        detail = detail.replace(city, '')
        break
      }
    }
  }

  // 查找区县
  if (foundCity && chinaRegions[foundProvince]?.[foundCity]) {
    const districts = chinaRegions[foundProvince][foundCity]
    for (const district of districts) {
      if (address.includes(district)) {
        foundDistrict = district
        detail = detail.replace(district, '')
        break
      }
    }
  }

  // 设置表单值
  if (foundProvince) {
    formData.province = foundProvince
    setTimeout(() => {
      if (foundCity) {
        formData.city = foundCity
        setTimeout(() => {
          if (foundDistrict) {
            formData.district = foundDistrict
          }
        }, 100)
      }
    }, 100)
  }

  formData.detailAddress = detail.trim().replace(/^[，,]\s*/, '')
}

const handleRecognize = () => {
  const text = textInput.value.trim()
  if (!text) {
    return
  }

  const lines = text.split('\n').filter(line => line.trim())
  if (lines.length > 0) {
    const firstLine = lines[0]
    const parts = firstLine.split(/[，,]/)

    if (parts.length >= 3) {
      formData.name = parts[0].trim()
      formData.phone = parts[1].trim()
      const address = parts.slice(2).join('').trim()
      parseAddress(address)

      // 成功提示
      showToast('识别成功！请检查并完善信息。', 'success')
    } else {
      showToast('文本格式不正确，请使用"姓名，手机号，地址"的格式', 'error')
    }
  }
}

const validateForm = () => {
  if (!formData.name.trim()) {
    showToast('请输入姓名', 'error')
    return false
  }

  if (!formData.phone.trim()) {
    showToast('请输入手机号', 'error')
    return false
  }

  const phonePattern = /^1[3-9]\d{9}$/
  if (!phonePattern.test(formData.phone.trim())) {
    showToast('请输入有效的手机号', 'error')
    return false
  }

  if (!formData.province) {
    showToast('请选择省份', 'error')
    return false
  }

  if (!formData.city) {
    showToast('请选择城市', 'error')
    return false
  }

  if (!formData.district) {
    showToast('请选择区县', 'error')
    return false
  }

  if (!formData.detailAddress.trim()) {
    showToast('请输入详细地址', 'error')
    return false
  }

  return true
}

const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true

  try {
    const currentUser = JSON.parse(sessionStorage.getItem('currentUser'))
    console.log(currentUser)
    const response = await addressAPI.create({
      name: formData.name.trim(),
      phone: formData.phone.trim(),
      province: formData.province,
      city: formData.city,
      district: formData.district,
      detailAddress: formData.detailAddress.trim(),
      createdBy: currentUser.username
    })

    if (response.success) {
      showToast('地址保存成功！', 'success')
      setTimeout(() => {
        router.push('/home')
      }, 1500)
    } else {
      showToast(response.message || '保存失败，请重试', 'error')
    }
  } catch (error) {
    showToast('保存失败，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/home')
}

// 简单的 toast 提示
const showToast = (message, type = 'info') => {
  // 这里可以集成一个 toast 组件，这里简单使用 alert
  alert(message)
}
</script>

<style scoped>
.new-address-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 导航栏样式 */
.navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 24px;
}

.logo-text {
  color: white;
  font-size: 1.4rem;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 40px 20px;
}

.container {
  max-width: 800px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 3rem;
  padding: 2rem 0;
}

.header-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  display: block;
}

.page-header h1 {
  color: #2d3748;
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  color: #718096;
  font-size: 1.1rem;
  font-weight: 400;
}

/* 卡片样式 */
.text-recognition-card,
.contact-form-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
  overflow: hidden;
  border: 1px solid #e2e8f0;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.text-recognition-card:hover,
.contact-form-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.15);
}

.card-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 1.5rem 2rem;
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header h2 {
  color: white;
  font-size: 1.4rem;
  font-weight: 600;
  margin: 0;
}

.card-icon {
  font-size: 1.5rem;
}

.card-content {
  padding: 2rem;
}

.section-description {
  color: #718096;
  margin-bottom: 1.5rem;
  line-height: 1.6;
  font-size: 0.95rem;
}

/* 文本输入区域 */
.text-input-container {
  margin-bottom: 1.5rem;
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.input-label {
  color: #2d3748;
  font-weight: 600;
  font-size: 0.95rem;
}

.char-count {
  color: #a0aec0;
  font-size: 0.85rem;
}

.styled-textarea {
  width: 100%;
  height: 140px;
  padding: 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 14px;
  resize: vertical;
  transition: all 0.3s ease;
  font-family: inherit;
  background: #f8fafc;
}

.styled-textarea:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.styled-textarea::placeholder {
  color: #a0aec0;
}

.input-footer {
  margin-top: 0.5rem;
}

.example-text {
  font-size: 0.85rem;
  color: #718096;
  display: flex;
  align-items: center;
  gap: 6px;
}

.hint-icon {
  font-size: 0.9rem;
}

/* 按钮样式 */
.recognize-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px 32px;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 auto;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.recognize-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.recognize-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 表单样式 */
.styled-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 600;
  color: #2d3748;
  font-size: 0.95rem;
}

.required-mark {
  color: #e53e3e;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 12px;
  font-size: 1.1rem;
  color: #a0aec0;
  z-index: 2;
}

.styled-input {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f8fafc;
  font-family: inherit;
}

.styled-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.styled-input::placeholder {
  color: #a0aec0;
}

/* 地址选择器 */
.address-selectors {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 1rem;
}

.select-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.select-icon {
  position: absolute;
  left: 12px;
  font-size: 1.1rem;
  color: #a0aec0;
  z-index: 2;
}

.styled-select {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f8fafc;
  cursor: pointer;
  appearance: none;
  font-family: inherit;
}

.styled-select:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.styled-select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 提示文本 */
.hint-text {
  margin-top: 0.5rem;
  font-size: 0.85rem;
  color: #718096;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e2e8f0;
}

.cancel-btn {
  background: #f7fafc;
  color: #4a5568;
  border: 2px solid #e2e8f0;
  padding: 12px 24px;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #edf2f7;
  border-color: #cbd5e0;
}

.save-btn {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  color: white;
  border: none;
  padding: 12px 32px;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(72, 187, 120, 0.3);
  min-width: 140px;
  justify-content: center;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(72, 187, 120, 0.4);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.btn-icon {
  font-size: 1.1rem;
}

/* 页脚 */
.footer {
  background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
  color: white;
  padding: 2rem 0;
  margin-top: 3rem;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  text-align: center;
  padding: 0 20px;
}

.footer-text {
  font-size: 1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.footer-subtext {
  font-size: 0.9rem;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    padding: 0 15px;
  }

  .logo-text {
    font-size: 1.2rem;
  }

  .page-header h1 {
    font-size: 2rem;
  }

  .main-content {
    padding: 20px 15px;
  }

  .card-content {
    padding: 1.5rem;
  }

  .form-row {
    grid-template-columns: 1fr;
    gap: 1rem;
  }

  .address-selectors {
    grid-template-columns: 1fr;
    gap: 0.75rem;
  }

  .form-actions {
    flex-direction: column;
  }

  .cancel-btn,
  .save-btn {
    width: 100%;
  }

  .styled-textarea {
    height: 120px;
  }
}

@media (max-width: 480px) {
  .card-header {
    padding: 1rem 1.5rem;
  }

  .card-header h2 {
    font-size: 1.2rem;
  }

  .page-header h1 {
    font-size: 1.8rem;
  }

  .header-icon {
    font-size: 2.5rem;
  }
}
</style>